package com.neudu.glsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neudu.glsb.pojo.ProductIngredient;
import com.neudu.glsb.service.ProductIngredientService;
import com.neudu.glsb.mapper.ProductIngredientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
* @author Lenovo
* @description 针对表【product_ingredient(商品-小料关联表)】的数据库操作Service实现
* @createDate 2025-09-20 11:25:07
*/
@Service
public class ProductIngredientServiceImpl extends ServiceImpl<ProductIngredientMapper, ProductIngredient>
    implements ProductIngredientService{
    @Autowired
    private ProductIngredientMapper productIngredientMapper;

    @Override
    public List<Map<String, Object>> getIngredientsByProductId(Integer productId) {
        return baseMapper.getIngredientsByProductId(productId);
    }
    // 新增1：获取商品可分配的小料（未关联的“小料”类型原料）
    @Override
    public List<Map<String, Object>> getOptionalIngredients(Integer productId) {
        // 1. 查询该商品已关联的小料ID，用于排除
        List<Integer> assignedIds = productIngredientMapper.selectAssignedIngredientIds(productId);
        // 2. 查询系统中所有“小料”类型且未关联的原料
        return productIngredientMapper.selectOptionalIngredients(assignedIds);
    }

    // 新增2：提交小料分配（事务保证原子性，避免部分成功）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignIngredients(Integer productId, List<ProductIngredient> newIngredients) {
        // 1. 删除该商品原有的所有小料关联
        LambdaQueryWrapper<ProductIngredient> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ProductIngredient::getProductId, productId);
        this.remove(deleteWrapper);

        // 2. 若无可分配的小料，直接返回成功
        if (CollectionUtils.isEmpty(newIngredients)) {
            return true;
        }

        // 3. 批量新增新的小料关联（设置商品ID）
        newIngredients.forEach(ingredient -> ingredient.setProductId(productId));
        return this.saveBatch(newIngredients);
    }
    public int removeOneIngredient(Integer productId, Integer ingredientId) {
        return baseMapper.deleteOne(productId, ingredientId);
    }
}




